package com.mini.mybatis.datasource.druid;

import com.mini.mybatis.datasource.DataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 简化版数据源工厂实现
 * 注意：这里为了简化，没有使用真正的Druid，而是使用简单的连接池实现
 */
public class DruidDataSourceFactory implements DataSourceFactory {
    
    private Properties props;
    
    @Override
    public void setProperties(Properties props) {
        this.props = props;
    }
    
    @Override
    public DataSource getDataSource() {
        return new SimpleDataSource(props);
    }
    
    /**
     * 简化版数据源实现
     */
    private static class SimpleDataSource implements DataSource {
        
        private final String driver;
        private final String url;
        private final String username;
        private final String password;
        
        public SimpleDataSource(Properties props) {
            this.driver = props.getProperty("driver");
            this.url = props.getProperty("url");
            this.username = props.getProperty("username");
            this.password = props.getProperty("password");
            
            // 加载数据库驱动
            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("找不到数据库驱动: " + driver, e);
            }
        }
        
        @Override
        public Connection getConnection() throws SQLException {
            return DriverManager.getConnection(url, username, password);
        }
        
        @Override
        public Connection getConnection(String username, String password) throws SQLException {
            return DriverManager.getConnection(url, username, password);
        }
        
        // 其他方法的简单实现
        @Override
        public <T> T unwrap(Class<T> iface) throws SQLException {
            throw new SQLException("不支持的操作");
        }
        
        @Override
        public boolean isWrapperFor(Class<?> iface) throws SQLException {
            return false;
        }
        
        @Override
        public java.io.PrintWriter getLogWriter() throws SQLException {
            throw new SQLException("不支持的操作");
        }
        
        @Override
        public void setLogWriter(java.io.PrintWriter out) throws SQLException {
            throw new SQLException("不支持的操作");
        }
        
        @Override
        public void setLoginTimeout(int seconds) throws SQLException {
            throw new SQLException("不支持的操作");
        }
        
        @Override
        public int getLoginTimeout() throws SQLException {
            return 0;
        }
        
        @Override
        public java.util.logging.Logger getParentLogger() {
            return java.util.logging.Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
        }
    }
}